package com.JWH_TV.dialog

import android.app.AlertDialog
import android.content.Context
import android.view.KeyEvent
import android.widget.EditText
import com.JWH_TV.domain.Program

class PasswordDialog(
    context: Context,
    private val program: Program,
    private val onPasswordCorrect: (String) -> Unit
) {

    private val dialog: AlertDialog

    init {
        val passwordEditText = EditText(context).apply {
            inputType = android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD
            hint = "请输入密码"
        }

        dialog = AlertDialog.Builder(context)
            .setTitle("请输入密码")
            .setView(passwordEditText)
            .setPositiveButton("确定", null)
            .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
            .create()

        passwordEditText.setOnKeyListener { _, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
                handlePasswordInput(passwordEditText.text.toString())
                true
            } else {
                false
            }
        }
    }

    fun show() {
        dialog.show()
    }

    private fun handlePasswordInput(inputPassword: String) {
        if (inputPassword == program.password) {
            onPasswordCorrect(inputPassword)
        } else {
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
        }
    }
}